package com.keyidea.jfxui.core.config.db;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;

@Configuration
@RequiredArgsConstructor
public class DataSourceInitConfig {

    private final DataSource dataSource;

    @PostConstruct
    public void executeSqlScript() throws SQLException, IOException {
        boolean flag = false;
        String property = System.getProperty("user.dir");
        File file = new File(property + "/db/jfx_ui.db");
        if (!file.exists()) {
            flag = true;
        } else {
            try (InputStream inputStream = new FileInputStream(file)) {
                if (inputStream.available() == 0) {
                    flag = true;
                }
            }
        }
        // data.db文件不存在或者data.db文件字节为0时，初始化数据库
        if (flag) {
            DatabasePopulator populator = new ResourceDatabasePopulator(
                    true,
                    false,
                    StandardCharsets.UTF_8.toString(),
                    new ClassPathResource("sql/schema-sqlite.sql"),
                    new ClassPathResource("sql/data-sqlite.sql")
            );
            populator.populate(dataSource.getConnection());
        }
    }
}
